﻿(function() {
  var Filter,
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  Filter = (function() {

    function Filter(element, options) {
      this.element = element;
      this.search = __bind(this.search, this);

      this.btn = $("#" + options.btnFilter);
      this.grid = $("#" + options.grid);
      this.init();
    }

    Filter.prototype.init = function() {
      var _this = this;
      this.element.on("keypress", function(e) {
        if (event.which !== 13 || $(e.target).is("textarea")) {
          return;
        }
        return _this.search();
      });
      return this.btn.on("click", this.search);
    };

    Filter.prototype.serialize = function() {
      return this.element.find(":input").serialize();
    };

    Filter.prototype.search = function() {
      return this.grid.jGrid("loadData", null, this.serialize(), null);
    };

    return Filter;

  })();

  $.fn.extend({
    filter: function(options) {
      var defaults, _arguments, _isMethod, _result;
      defaults = {
        grid: null,
        btnFilter: null
      };
      _isMethod = typeof options === "string";
      _arguments = Array.prototype.slice.call(arguments, 1);
      _result = this;
      this.each(function() {
        var element, obj;
        element = $(this);
        obj = element.data("rhd.filter");
        if ((obj != null) && !_isMethod) {
          return;
        }
        if (_isMethod) {
          return _result = obj[options].apply(obj, _arguments);
        } else {
          options = $.extend(defaults, options);
          return $(this).data("rhd.filter", new Filter(element, options));
        }
      });
      return _result;
    }
  });

}).call(this);
